package com.weibo.survey.controller;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.weibo.survey.domain.User;

public class LoginInterceptor implements Interceptor {
	private static final long serialVersionUID = 1L;

	@Override
	public void destroy() {

	}

	@Override
	public void init() {

	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		BaseAction<?> baseAction = (BaseAction<?>) invocation.getAction();
		if (baseAction instanceof LoginAction || baseAction instanceof RegisterAction) {
			return invocation.invoke();
		} else {
			HttpSession session = ServletActionContext.getRequest().getSession();
			User user = (User) session.getAttribute("user");
			if (user == null) {
				return "login";
			} else {
				if (baseAction instanceof UserAware) {
					UserAware userAware = (UserAware) baseAction;
					userAware.setUser(user);
				}
				return invocation.invoke();
			}
		}
	}

}
